package com.zego.wawaji.ui.play;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.zego.wawaji.R;
import com.zego.wawaji.base.Constant;
import com.zego.wawaji.base.log.PSP;
import com.zego.wawaji.base.log.PToast;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.observer.MsgMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.zego.wawaji.base.utils.MediaNotifyUtils;
import com.zego.wawaji.http.request.HttpResponse;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.ui.activity.LogListActivity;
import com.zego.wawaji.ui.bean.wawa.WawaJi;
import com.zego.wawaji.ui.dialog.CatchWawaDialog;
import com.zego.wawaji.ui.dialog.PickerDialogUtil;
import com.zego.wawaji.wawaji_client.App;
import com.zego.wawaji.wawaji_client.cmd.CommandUtil;
import com.zego.wawaji.wawaji_client.play.BoardState;
import com.zego.wawaji.wawaji_client.play.PlayStatus;
import com.zego.wawaji.wawaji_client.util.PreferenceUtil;
import com.zego.zegoliveroom.ZegoLiveRoom;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 游戏帮助类
 */
public class PlayHelper {
    public static int mSwitchCameraTimes = 0;     // 切换摄像头次数, 重定义方向键

    public static void setSwitchTimes(int times) {
        mSwitchCameraTimes = times;
    }

    /**
     * 查看日志弹框
     */
    public static void showLogMenu(final Activity context) {
        final Dialog mDialog = new Dialog(context);
        View viewBottom = LayoutInflater.from(context).inflate(R.layout.dialog_bottom, null);

        TextView tvUserID = (TextView) viewBottom.findViewById(R.id.tv_user_id);
        tvUserID.setText("UserID: " + PreferenceUtil.getInstance().getUserID());
        tvUserID.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(PreferenceUtil.getInstance().getUserID());
                Toast.makeText(context, "已复制到剪贴板", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        viewBottom.findViewById(R.id.btn_log_list).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogListActivity.actionStart(context);
            }
        });

        viewBottom.findViewById(R.id.btn_upload_log).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ZegoLiveRoom.uploadLog();
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "上传日志成功!", Toast.LENGTH_SHORT).show();
                    }
                }, 2000);
            }
        });

        viewBottom.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });

        mDialog.setContentView(viewBottom);
        Window dialogWindow = mDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;
        dialogWindow.setAttributes(lp);
        mDialog.show();
    }

    private static CountDownTimer mCountDownTimerReplay; // 重玩倒计时

    /**
     * 处理游戏结果
     */
    public static void handleGameResult(Context context, final int rspSeq, Map<String, Object> data) {
        if (data == null) {
            CommandUtil.getInstance().printLog("[handleGameResult], data is null");
            return;
        }
        int result = ((Double) data.get("result")).intValue();  // 游戏结果

        Map<String, Object> player = (Map<String, Object>) data.get("player");
        if (player == null) {
            CommandUtil.getInstance().printLog("[handleGameResult], player is null");
            return;
        }

        // 不是自己的通知，如果是成功记录,通知房间内用户抓中记录, 否则抛掉
        if (!PreferenceUtil.getInstance().getUserID().equals(player.get("id"))) {
            CommandUtil.getInstance().printLog("[handleGameResult], not my message, don't care");
            if (result == 1) {
                handleSucResult(player);
            }
            return;
        }

        // 发送确认游戏结果CMD, 雪豹，苏瑞娃娃机使用
        if (PlayStatus.getCurrentBoardSate() != BoardState.WaitingGameResult) {
            String sessionData = (String) data.get("session_data");
            CommandUtil.getInstance().confirmGameResult(rspSeq, sessionData);
            return;
        }

        final String sessionData = (String) data.get("session_data");
        PlayStatus.setCurrentBoardSate(BoardState.WaitingReplay);
        final CatchWawaDialog catchWawaDialog = new CatchWawaDialog((FragmentActivity) App.getActivity());
        catchWawaDialog.setCancelableOutTouch(false);
        catchWawaDialog.show();
        int gameResult = 1;
        if (result != 1) {  // 未抓中
            gameResult = -1;
            catchWawaDialog.setTitle("好遗憾，没有抓中哎！");
            catchWawaDialog.setImgCenter(R.drawable.play_catch_no);
        } else {
            playGameResultSound();
            handleSucResult(player);
        }

        final WawaJi wawaJi = ModuleMgr.getWawaMgr().getLastWawaJi();
        catchWawaDialog.setPositiveButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                catchWawaDialog.dismiss();
                mCountDownTimerReplay.cancel();
                ModuleMgr.getWawaMgr().reqGameApply(wawaJi.getId(), wawaJi.getWwTypeId(), new RequestComplete() {
                    @Override
                    public void onRequestComplete(HttpResponse response) {
                        if (!response.isOk()) {
                            MsgMgr.getInstance().sendMsg(MsgType.MT_Re_Init_Game, null);
                            return;
                        }
                        // 确认上机
                        CommandUtil.getInstance().confirmBoard(rspSeq, sessionData, 1, new CommandUtil.OnCommandSendCallback() {
                            @Override
                            public void onSendFail() {
                                PToast.showShort("连接服务器失败了, 请重新开始预约!");
                            }
                        });
                    }
                });
            }
        });
        // 放弃上机
        catchWawaDialog.setNegativeButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCountDownTimerReplay.cancel();
                MsgMgr.getInstance().sendMsg(MsgType.MT_Re_Init_Game, null);
                CommandUtil.getInstance().confirmBoard(rspSeq, sessionData, 0, null);
                catchWawaDialog.dismiss();
            }
        });

        mCountDownTimerReplay = new CountDownTimer(5000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (PlayStatus.getCurrentBoardSate() == BoardState.WaitingReplay) {
                    catchWawaDialog.setCountTimes(App.getActivity().getString(R.string.game_replay, ((millisUntilFinished / 1000) + 1) + ""));
                }
            }

            @Override
            public void onFinish() {
                if (PlayStatus.getCurrentBoardSate() == BoardState.WaitingReplay) {
                    CommandUtil.getInstance().confirmBoard(rspSeq, sessionData, 0, null);
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Re_Init_Game, null);
                    catchWawaDialog.dismiss();
                }
            }
        }.start();
    }

    /**
     * 处理游戏抓中结果
     */
    private static void handleSucResult(Map<String, Object> player) {
        MsgMgr.getInstance().sendMsg(MsgType.MT_Game_Suc, player);
    }

    /**
     * 是否准备游戏弹框
     */
    public static void handleGameReady(FragmentActivity activity, final int rspSeq, Map<String, Object> data) {
        if (data == null) {
            return;
        }

        // 处于等待重玩游戏
        if (PlayStatus.getCurrentBoardSate() == BoardState.WaitingReplay) {
            return;
        }

        Map<String, Object> player = (Map<String, Object>) data.get("player");
        if (player == null) return;

        // 不是自己的消息
        if (!PreferenceUtil.getInstance().getUserID().equals(player.get("id"))) {
            return;
        }

        if (PlayStatus.getCurrentBoardSate() == BoardState.Applying) {
            PlayStatus.setCurrentBoardSate(BoardState.WaitingBoard);
        }

        if (PlayStatus.getCurrentBoardSate() != BoardState.WaitingBoard) {
            return;
        }
        final String sessionData = (String) data.get("session_data");
        PickerDialogUtil.showStartGameDialog(activity, rspSeq, sessionData);
    }

    public static void reset() {
        releasePlay();
        MediaNotifyUtils.stopSound();
        mSwitchCameraTimes = 0;
        if (mCountDownTimerReplay != null) {
            mCountDownTimerReplay.cancel();
        }
    }

    // ================================== 音乐管理 =====================
    private static List<MediaPlayer> mediaPlayerList = new ArrayList<>();  // 维护播放对象

    /**
     * 注册
     */
    public static void attachPlayer(MediaPlayer mMediaPlayer) {
        if (mediaPlayerList == null)
            mediaPlayerList = new ArrayList<>();
        mediaPlayerList.add(mMediaPlayer);
    }

    private static MediaPlayer bgmMedia;
    private static AssetFileDescriptor afd;

    /**
     * 背景音乐
     */
    public static void playSound() {
        boolean isPlay = PSP.getInstance().getBoolean(Constant.SET_BGM, true);
        if (!isPlay) return;

        try {
            if (afd == null) {
                AssetManager assetManager = App.getContext().getAssets();
                afd = assetManager.openFd("ring01.mp3");
            }
            bgmMedia = new MediaPlayer();
            attachPlayer(bgmMedia);
            bgmMedia.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
            bgmMedia.setLooping(false);
            bgmMedia.prepare();
            bgmMedia.start();
            bgmMedia.setVolume(0.5f, 0.5f);

            bgmMedia.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    bgmMedia.start();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void stopPlay() {
        if (mediaPlayerList == null) return;
        for (MediaPlayer mediaPlayer : mediaPlayerList) {
            mediaPlayer.stop();
        }
    }

    public static void releasePlay() {
        if (mediaPlayerList == null) return;
        for (MediaPlayer mediaPlayer : mediaPlayerList) {
            mediaPlayer.release();
        }
        mediaPlayerList.clear();
    }

    private static AssetFileDescriptor btnAfd;

    /**
     * 按钮点击音效
     */
    public static void playBtnSound() {
        boolean isPlay = PSP.getInstance().getBoolean(Constant.SET_VOICE, true);
        if (!isPlay) return;

        try {
            if (btnAfd == null) {
                AssetManager assetManager = App.getContext().getAssets();
                btnAfd = assetManager.openFd("btn.wav");
            }
            MediaNotifyUtils.playSound(btnAfd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static AssetFileDescriptor gameAfd;

    /**
     * 抓中游戏音效
     */
    public static void playGameResultSound() {
        boolean isPlay = PSP.getInstance().getBoolean(Constant.SET_BGM, true);
        if (!isPlay) return;


        try {
            if (gameAfd == null) {
                AssetManager assetManager = App.getContext().getAssets();
                gameAfd = assetManager.openFd("catch.wav");
            }
            MediaNotifyUtils.playSound(gameAfd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
